/* Includes ------------------------------------------------------------------*/
#include "public.h"
#include "bsp_pwm.h"

#include "stc15.h"
/* Private define-------------------------------------------------------------*/
#define CCP_S1  BIT5
#define CCP_S0  BIT4   

#define EPC0H   BIT1
#define EPC0L   BIT0
/* Private variables----------------------------------------------------------*/
static void PWM_Init();
static void PWM_LED_Adjust_Brightness();
/* Public variables-----------------------------------------------------------*/
PWM_t PWM = {Duty_20,PWM_Init,PWM_LED_Adjust_Brightness};
/* Private function prototypes------------------------------------------------*/

/*
* @name   PWM_Init
* @brief  PWM初始化
* @param  None
* @retval None   
*/
static void PWM_Init()
{
    //选择管脚，因为开发板的PWM灯接到了P3.5口
    //将BIT5的CCP_S1清0，BIT4的CCP_S0置1，即可将CCP切换到P3.5管脚
    AUXR1 &= ~(CCP_S1); 
    AUXR1 |= (CCP_S0);

    //CCON里都是一些标志位，全置0即可
    /*CMOD 的BIT7置0，设置空闲模式下PAC计数器继续工作;BIT3、BIT2、BIT1置为110，
    系统时钟6分频，SYSclk/6*/
    CCON = 0x00;
    CMOD = 0x0C;

    //用于保存PCA装载值的16位计数器都清零
    CL = 0;
    CH = 0;

    //BIT6置1，允许比较器功能；BIT1置1，允许CCP0脚用作脉宽调节输出
    //PCA_PWM0的BIT7和BIT6置0，使模块工作于8位PWM模式，BIT1和BIT0的EPC0H和EPC0L清0
    CCAPM0 = 0x42;
    PCA_PWM0 = 0x00;

    //设置默认亮度，占空比20%
    //CCAP0H初值计算公式：CCAP0H = （1-要设置的占空比）*256
    PCA_PWM0 &= ~(EPC0H);   //EPC0H = 0,EPC0L = 1
    CCAP0H = 204;

    //将CCAP0H的值装载到CCAP0L中
    PCA_PWM0 &= ~(EPC0L);   //EPC0H = 1,EPC0L = 0
    CCAP0L = CCAP0H;
		
    CR = 1;
}

/*
* @name   PWM_LED_Adjust_Brightness
* @brief  PWM灯调整亮度
* @param  None
* @retval None   
*/
static void PWM_LED_Adjust_Brightness()
{
    uint8_t  Temp_Value = 0;

	/*初始化时PWM.Duty的值为Duty_20，单击按下后，进入该switch语句
	PWM.Duty 被修改为Duty_40，占空比变量Temp_Value被赋值153，然后
	跳出switch语句，后面对CCAP0H赋值，输出占空比
	下次再单击按键，进入switch，匹配case Duty_40，所以PWM.Duty会
	再次被改变为Duty_60，占空比输出102即60%*/
	switch (PWM.Duty)
	{
	  case Duty_0:    PWM.Duty = Duty_20;   Temp_Value = 204;break;
	  case Duty_20:   PWM.Duty = Duty_40;   Temp_Value = 153;break;
	  case Duty_40:   PWM.Duty = Duty_60;   Temp_Value = 102;break;
	  case Duty_60:   PWM.Duty = Duty_80;   Temp_Value = 51;break;
	  case Duty_80:   PWM.Duty = Duty_100;  break;
	  case Duty_100:  PWM.Duty = Duty_0;    break;
	  default: PWM.Duty = Duty_0; break;
	}
	
	//亮度调节
	//占空比为0%，全输出低电平，PWM灯灭
	if(PWM.Duty == 0)
	{
	  PCA_PWM0 |= (EPC0H);
	  CCAP0H = 0xFF;

	  PCA_PWM0 |= (EPC0L);		//置1则表示9位数，加上CCAP0L最大去到511
	  CCAP0L = CCAP0H;
	}
	//占空比为100%，全输出高电平，PWM灯全亮
	else if(PWM.Duty == 100)
	{
	  PCA_PWM0 &= ~(EPC0H);
	  CCAP0H = 0x00;
	  PCA_PWM0 &= ~(EPC0L);
	  CCAP0L = 0x00;
	}
	else
	{
		//根据Temp_Value设置的值修改占空比
	   PCA_PWM0 &= ~(EPC0H);	//~0000 0010  ->  1111 1101	即让EPC0H为0
	   CCAP0H = Temp_Value;
	   PCA_PWM0 &= ~(EPC0L);	//因为上一步将BIT0，即EPC0L位置1了，所以也让该位清0后，CCAP0H再赋值给CCAP0L
	   CCAP0L = CCAP0H;
	}
    
}

/********************************************************
  End Of File
********************************************************/